package com.example.action;

import com.example.bean.*;
import com.example.service.OrderService;
import com.example.util.UUIDUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

@WebServlet("/submitOrder")
public class SubmitOrderServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取购物车（session）
        // 新建订单
        // 保存订单
        // 清空购物车
        // 请求转发到订单页面
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        Order order = new Order();
        order.setTotal(cart.getTotal());
        order.setOid(UUIDUtils.getId());
        order.setState(1);
        order.setOrderTime(new Date());
        User user = (User) req.getSession().getAttribute("loginUser");
        order.setUid(user.getId());
        for (CartItem item : cart.getCartItems()) {
            OrderItem orderItem = new OrderItem();
            orderItem.setItemId(UUIDUtils.getId());
            orderItem.setCount(item.getCount());
            orderItem.setSubtotal(item.getSubtotal());
            orderItem.setProduct(item.getProduct());
            orderItem.setOid(order.getOid());
            order.getList().add(orderItem);
        }
        OrderService orderService = new OrderService();
        try {
            orderService.saveOrder(order);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        cart.clearCart();
        req.setAttribute("order", order);
        req.getRequestDispatcher("order_info.jsp").forward(req, resp);
    }
}
